/**
 * $Revision: 1.0 $
 * $Author: Eric Yang $
 * $Date: Dec 6, 2009 11:55:14 AM $
 *
 * Author: Eric Yang
 * Date  : Dec 6, 2009 11:55:14 AM
 *
 */
package com.gooex.service.organization.impl;

import java.util.List;
import org.hibernate.Query;
import org.c4j.string.StringTools;
import org.c4j.system.web.exception.ServiceException;

import com.gooex.domain.organization.Address;
import com.gooex.domain.organization.User;
import com.gooex.service.BaseAppHibernateService;
import com.gooex.service.organization.IAddressManager;

/**
 * @author Eric Yang
 * @version 1.0
 */
public class AddressManagerImpl extends BaseAppHibernateService implements IAddressManager {

	public Address getAddress(String id) {
		if (StringTools.isBlankOrNull(id))
			return null;
		return (Address) getHibernateTemplate().get(Address.class, id);
	}

	public List<Address> getUserAddresses(User user) {
		Query query = getSession().createQuery("from " + Address.class.getName() + " where user.id=:userId");
		query.setParameter("userId", user.getId());
		return query.list();
	}

	public long getUserAddressNum(User user) {
		Query query = getSession().createQuery("select count(*) from " + Address.class.getName() + " where user.id=:userId");
		query.setParameter("userId", user.getId());
		return (Long) query.uniqueResult();
	}

	public Address getUserAddresses(String addressId, User user) {
		Query query = getSession().createQuery("from " + Address.class.getName() + " where id=:addressId and user.id=:userId");
		query.setParameter("addressId", addressId);
		query.setParameter("userId", user.getId());
		List<Address> list = query.list();
		if (list != null && list.size() > 0)
			return list.get(0);
		return null;
	}

	public void removeAddress(Address address) throws ServiceException {
		address = getAddress(address.getId());
		getHibernateTemplate().delete(address);
	}

	public void saveAddress(Address address) {
		if (StringTools.isBlankOrNull(address.getId())) {
			address.setId(null);
			address.setUser(getCurrentUser());
		}
		getHibernateTemplate().saveOrUpdate(address);
	}

}
